
package com.zhu.salesmanagement;

import java.util.ArrayList;

import com.dms2.salesmanagement.R;
import com.zhu.salesmanagement.common.Actions;
import com.zhu.salesmanagement.common.MyLocation;
import com.zhu.salesmanagement.common.MyLocation.LocationResult;
import com.zhu.salesmanagement.models.RemindItemInfo;
import com.zhu.salesmanagement.models.VisitTaskInfo;
import com.zhu.salesmanagement.network.PutCustomerData;
import com.zhu.salesmanagement.provider.SalesSettings;
import com.zhu.salesmanagement.utils.Util;
import com.zhu.salesmanagement.views.ObservableScrollView;
import com.zhu.salesmanagement.views.ProductInfoListView;

import android.app.Activity;
import android.app.Dialog;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.graphics.drawable.AnimationDrawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

/**
 * 清单拜访界面
 */
public class VisitTaskListActivity extends Activity implements View.OnClickListener {

	private final static String TAG = "VisitTaskListActivity";
	private final static int TASK_LIST_QUERY_TOKEN = 1000;
	private final static int CNAME_LIST_QUERY_TOKEN = 1001;
	private final static int CREMIND_LIST_QUERY_TOKEN = 1003;
    private final static int TASK_LIST_DELETE_TOKEN = 2000;
    private static final int UPDATE_DB = 1000;
    public static final String STARTCHECKID = "00000000";
    public static final String STOPCHECKID = "99999999";
	public static final int CHECK_IN = 0;
	public static final int CHECK_OUT = 1;
    private ObservableScrollView mScrollView;
    private LinearLayout mBodyLinearLayout = null;
    private ArrayList<VisitTaskInfo> mVisitTaskList = null;
    private TextView mScollClew = null;
    private TextView mNoneTextView = null;
    private View mCheckView = null;
    private FrameLayout mFrameLayout = null;
    private int mCurCheckType = -1;
    private boolean isChecking = false;
    private AnimationDrawable mAnimation = null;
    private MyLocation mMyLocation = null;
    private Location mCurLocation = null;
    private VisitTaskInfo mCheckingVisitTaskInfo = null;
    private ImageView mCheckingButtom = null;
    private int mVisitedCount = 0;
    private DataQueryHandler mDataQueryHandler = null;
    private PutCustomerData mSyncCustomerData = null; //门店数据上传

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.visittasklist_main);

        mVisitTaskList = new ArrayList<VisitTaskInfo>();

        setupViews();

        mDataQueryHandler = new DataQueryHandler(this.getContentResolver());

        init();
    }

    public void onResume() {
        super.onResume();
        Actions.setAutoTime(this);
    }

    /**
     * 初始化界面
     */
    private void setupViews() {
        mScrollView = (ObservableScrollView) findViewById(R.id.visitTaskcontent_scrollview);
        mScrollView.setScrollViewListener(mScrollViewListener);
        mNoneTextView = (TextView) findViewById(R.id.none_text);
        mNoneTextView.setVisibility(View.VISIBLE);

        mScollClew = (TextView) findViewById(R.id.visitTask_scrollclew);
        mBodyLinearLayout = (LinearLayout) findViewById(R.id.visitTaskcontent_view_bodyView);
        mFrameLayout = (FrameLayout)findViewById(R.id.visittask_layout); 

        findViewById(R.id.visit_back).setOnClickListener(this);

        findViewById(R.id.visittask_addstore).setOnClickListener(this);
        findViewById(R.id.visittask_back).setOnClickListener(this);
    }

    /**
     * 初始化数据
     */
    private void init(){
    	startTaskListAsyncQuery();
    }

    /**
     * 获取清单拜访列表
     */
    private void startTaskListAsyncQuery() {
        try {
        	mDataQueryHandler.startQuery(TASK_LIST_QUERY_TOKEN, null,
                    SalesSettings.VisitedStoresColumns.CONTENT_URI,
                    null, null, null, SalesSettings.VisitedStoresColumns.ITEMNO + " ASC");
        } catch (SQLiteException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新清单拜访数据
     * @param cursor 数据库数据
     */
    private void updateList(Cursor cursor) {
        mVisitTaskList.clear();
        mVisitedCount = 0;

        String where = "";
        try {
            final int idIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns._ID);
            final int storeidIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.STOREID);
            final int itemnoIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.ITEMNO);
            final int checkintimeIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKIN_TIME);
            final int checkresultIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKRESULT);
            final int checkinfoIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.CHECKRINFO);
            final int pustatusIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.PUTSTATUS);
            final int putsuccessIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.PUTSUCCESS);
            final int dtidIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns.DTASKACTUALID);

            while (cursor.moveToNext()) {
            	String cid = cursor.getString(storeidIndex);
            	String checkintime = cursor.getString(checkintimeIndex);

            		VisitTaskInfo visitTaskInfo = new VisitTaskInfo();
                	visitTaskInfo.mDbId = cursor.getLong(idIndex);
                	visitTaskInfo.id = cid;
                	visitTaskInfo.itemId = cursor.getInt(itemnoIndex);
                	visitTaskInfo.mCheckinTime = checkintime;
                	visitTaskInfo.sCheckResult = cursor.getString(checkresultIndex);
                	visitTaskInfo.sCheckInfo = cursor.getString(checkinfoIndex);
                	visitTaskInfo.canPut = cursor.getInt(pustatusIndex) == 1 ? true : false;
                	visitTaskInfo.isPutSuccess = cursor.getInt(putsuccessIndex) == 1 ? true : false;
                	visitTaskInfo.mDatingTaskActualID = cursor.getString(dtidIndex);
                	//if(!visitTaskInfo.isClosed){
                		mVisitTaskList.add(visitTaskInfo);
                    	if(where.length() == 0){
                    		where = SalesSettings.CustomerSColumns.CUSTOMER_ID + " = \"" + visitTaskInfo.id +"\"";
                    	}else{
                    		where += " OR "+ SalesSettings.CustomerSColumns.CUSTOMER_ID +" = \"" + visitTaskInfo.id +"\"";
                    	}
                	//}
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "updateList error");
        } finally {
        	if(cursor != null){
        		cursor.close();
        	}
        }

        try {
        	mDataQueryHandler.startQuery(CNAME_LIST_QUERY_TOKEN, null,
                    SalesSettings.CustomerSColumns.CONTENT_URI,
                    null, where, null, null);
        } catch (SQLiteException e) {
            e.printStackTrace();
        }

        updateInfoTextview(mVisitTaskList.size(), mVisitedCount);
    }

    /**
     * 更新门店信息数据
     * @param cursor 数据库数据
     */
    private void updateStoreInfoList(Cursor cursor) {
    	 try {
             final int idIndex = cursor.getColumnIndexOrThrow(SalesSettings.VisitedStoresColumns._ID);
             final int storeidIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_ID);
             final int nameIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_NAME);
             final int typeIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_VISITCODE);
             final int latIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_LAT);
             final int lngIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_LNG);
             final int addrIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_ADDRESS);
             final int propertyIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_PROPERTY);
             final int areaidIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_AREAID);
             final int crctimeIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_CRCNEARTIME);
             final int sctimeIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_SCNEARTIME);
             final int dealernameIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_DEALERNAME);
             final int scategortIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.CUSTOMER_SCATEGORT);
             final int msgIndex = cursor.getColumnIndexOrThrow(SalesSettings.CustomerSColumns.IMPORTANTINFO);

             while (cursor.moveToNext()) {
            	String sid = cursor.getString(storeidIndex);
             	VisitTaskInfo visitTaskInfo = getVisitTaskInfo(sid);
             	if(visitTaskInfo != null){
                    visitTaskInfo.mName = cursor.getString(nameIndex);
                    visitTaskInfo.mAddress = cursor.getString(addrIndex);
                    if(Actions.DEBUG){
                        Log.e("zhu", cursor.getString(typeIndex));
                    }
                    visitTaskInfo.type = Integer.parseInt(cursor.getString(typeIndex));
                    visitTaskInfo.mLatitude = Double.parseDouble(cursor.getString(latIndex));
                    visitTaskInfo.mLongitude = Double.parseDouble(cursor.getString(lngIndex));
                    visitTaskInfo.iProperty = cursor.getInt(propertyIndex);
                    visitTaskInfo.sAreaID = cursor.getString(areaidIndex);
                    visitTaskInfo.sDealtSalesPerson = cursor.getString(dealernameIndex);
                    visitTaskInfo.sCRCNearTime = cursor.getString(crctimeIndex);
                    visitTaskInfo.sSCNearTime = cursor.getString(sctimeIndex);
                    visitTaskInfo.sStoreCategory = cursor.getString(scategortIndex);
                    visitTaskInfo.sMsg = cursor.getString(msgIndex);

                    if(Actions.DEBUG){
                       Log.e("zhu", visitTaskInfo.mLatitude+","+visitTaskInfo.mLongitude);
                    }
             	}
             }
         } catch (Exception e) {
             e.printStackTrace();
             Log.e("zhu", "updateStoreInfoList error");
         } finally {
        	 if(cursor != null){
        		 cursor.close();
        	 }
         }

//         try {
//             mDataQueryHandler.startQuery(CREMIND_LIST_QUERY_TOKEN, null,
//                     SalesSettings.RemindsColumns.CONTENT_URI,
//                     null, null, null, null);
//         } catch (SQLiteException e) {
//             e.printStackTrace();
//         }

         updateView();
    }

    /**
     * 更新门店提醒数据
     * @param cursor 数据库数据
     */
    private void updateStoreRemindInfoList(Cursor cursor) {
        try {
            final int cidIndex = cursor.getColumnIndexOrThrow(SalesSettings.RemindsColumns.CUSTOMERID);
            final int timeIndex = cursor.getColumnIndexOrThrow(SalesSettings.RemindsColumns.TIME);

            while (cursor.moveToNext()) {
                String cid = cursor.getString(cidIndex);
                if(cid != null && cid.trim().length() > 0){
                    VisitTaskInfo visitTaskInfo = getVisitTaskInfo(cid);
                    if(Long.parseLong(cursor.getString(timeIndex)) > System.currentTimeMillis()){
                        visitTaskInfo.hasRemind = true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e("zhu", "update Remind ListData error");
        } finally {
            cursor.close();
        }

        updateView();
   }

    /**
     * 更新列表界面
     */
    private void updateView(){
		mBodyLinearLayout.removeAllViews();
		View view = null;
		for (int i = 0; i < mVisitTaskList.size(); i++) {
			VisitTaskInfo visitTaskInfo = mVisitTaskList.get(i);
			if(visitTaskInfo.isClosed){
                if(visitTaskInfo.type == VisitTaskInfo.STORE_DEALER){
                    view = getDealerClosedTaskItem(visitTaskInfo);
                }else{
                    view = getClosedTaskItem(visitTaskInfo);
                }
            } else if(visitTaskInfo.isVisited){
				if(visitTaskInfo.type == VisitTaskInfo.STORE_DEALER){
					view = getDealerVisitedTaskItem(visitTaskInfo);
				}else{
					view = getVisitedTaskItem(visitTaskInfo);
				}
			}else{
				if(visitTaskInfo.type == VisitTaskInfo.STORE_DEALER){
					view = getDealerVisitTaskItem(visitTaskInfo);
				}else{
					view = getVisitTaskItem(visitTaskInfo);
				}
			}
			mBodyLinearLayout.addView(view);
		}
		if(mBodyLinearLayout.getChildCount() > 0){
			mNoneTextView.setVisibility(View.GONE);
		}else{
			mNoneTextView.setVisibility(View.VISIBLE);
		}

		mScrollView.post(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (mScrollView.canScrollView()) {
					mScollClew.setVisibility(View.VISIBLE);
				}
			}
		});
	}

    /**
     * 根据门店ID获取门店信息
     * @param sid 门店ID
     */
    private VisitTaskInfo getVisitTaskInfo(String sid){
    	for(int i = 0; i < mVisitTaskList.size(); i++){
    		VisitTaskInfo visitTaskInfo = mVisitTaskList.get(i);
    		if(visitTaskInfo.id.equals(sid)){
    			return visitTaskInfo;
    		}
    	}
    	return null;
    }

    /**
     * 获取门店列表项界面
     * @param info 门店信息
     */
    private View getVisitTaskItem(VisitTaskInfo info) {
        View row = LayoutInflater.from(this).inflate(R.layout.home_visittasklist_item, null);
        View content = row.findViewById(R.id.home_visitTasRowContent);
        TextView name = (TextView) row.findViewById(R.id.home_visitTastname);
        name.setText(info.mName);
        content.setTag(info);
        ImageView task = (ImageView) row.findViewById(R.id.home_visitTast);
        //task.setTag(info);
        //task.setOnClickListener(this);
//        if(info.mCheckinTime != null && info.mCheckinTime.length() > 2){
//            task.setImageResource(R.drawable.icon_checkout);
//        }else{
        task.setImageDrawable(null);
//        }
        if(info.canPut){
            task.setImageResource(R.drawable.icon_shangchuan);
        }
        if(info.isPutSuccess){
            task.setImageResource(R.drawable.icon_ok);
            name.setTextColor(getResources().getColor(R.color.visit_gray));
        }else{
        	content.setOnClickListener(this);
        }
        return row;
    }

    /**
     * 获取经销商拜访任务列表项
     * @param info 门店信息
     */
    private View getDealerVisitTaskItem(VisitTaskInfo info) {
        View row = LayoutInflater.from(this).inflate(R.layout.dealer_visittasklist_item, null);
        View content = row.findViewById(R.id.home_visitTasRowContent);
        content.setTag(info);
        content.setOnClickListener(this);
        ImageView task = (ImageView) row.findViewById(R.id.home_visitTast);
        //task.setTag(info);
        //task.setOnClickListener(this);
        if(info.mCheckinTime != null && info.mCheckinTime.length() > 2){
            task.setImageResource(R.drawable.icon_checkout);
        }else{
            task.setImageDrawable(null);
        }
        if(info.isPutSuccess){
            task.setImageResource(R.drawable.icon_shangchuan);
        }
        TextView name = (TextView) row.findViewById(R.id.home_visitTastname);
        name.setText(info.mName);
        return row;
    }

    /**
     * 获取已拜访任务列表项
     * @param info 门店信息
     */
    private View getVisitedTaskItem(VisitTaskInfo info) {
        View row = LayoutInflater.from(this).inflate(R.layout.visitedtasklist_item, null);
        View content = row.findViewById(R.id.home_visitTasRowContent);
        content.setTag(info);
        content.setOnClickListener(this);
        TextView name = (TextView) row.findViewById(R.id.home_visitTastname);
        name.setText(info.mName);
        return row;
    }

    /**
     * 获取歇业任务列表项
     * @param info 门店信息
     */
    private View getClosedTaskItem(VisitTaskInfo info) {
        View row = LayoutInflater.from(this).inflate(R.layout.visitedtasklist_item, null);
        View content = row.findViewById(R.id.home_visitTasRowContent);
        //content.setTag(info);
        //content.setOnClickListener(this);
        TextView name = (TextView) row.findViewById(R.id.home_visitTastname);
        name.setText(info.mName);
        ImageView image = (ImageView) row.findViewById(R.id.visited_status);
        image.setImageResource(R.drawable.icon_off);
        return row;
    }

    /**
     * 获取经销商已拜访任务列表项
     * @param info 门店信息
     */
    private View getDealerVisitedTaskItem(VisitTaskInfo info) {
        View row = LayoutInflater.from(this).inflate(R.layout.dealvisitedtasklist_item, null);
        View content = row.findViewById(R.id.home_visitTasRowContent);
        content.setTag(info);
        content.setOnClickListener(this);
        TextView name = (TextView) row.findViewById(R.id.home_visitTastname);
        name.setText(info.mName);
        return row;
    }

    /**
     * 获取经销商歇业任务列表项
     * @param info 门店信息
     */
    private View getDealerClosedTaskItem(VisitTaskInfo info) {
        View row = LayoutInflater.from(this).inflate(R.layout.dealvisitedtasklist_item, null);
        View content = row.findViewById(R.id.home_visitTasRowContent);
        //content.setTag(info);
        //content.setOnClickListener(this);
        TextView name = (TextView) row.findViewById(R.id.home_visitTastname);
        name.setText(info.mName);
        ImageView image = (ImageView) row.findViewById(R.id.dealvisited_status);
        image.setImageResource(R.drawable.icon_off);
        return row;
    }

    private void updateInfoTextview(int needVisitCount, int visitedCount) {
//        String info = getResources().getString(R.string.needvisitTask) + "<font color=#FF3030>"
//                + needVisitCount + "</font>" + getResources().getString(R.string.visitedCount)
//                + getResources().getString(R.string.douhao)
//                + getResources().getString(R.string.visitedTask) + "<font color=#FF3030>"
//                + visitedCount + "</font>" + getResources().getString(R.string.visitedCount);
//        String text = getResources().getString(R.string.visitclew, needVisitCount, (needVisitCount - visitedCount));
//        mVisitTaskinfoTextView.setText(text/*Html.fromHtml(info)*/);
    }

    /**
     * 点击事件处理
     */
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v != null) {
            switch (v.getId()) {
                case R.id.home_visitTasRowContent: //拜访弹框
                    if(canVisit()){
                        /*VisitTaskInfo info = (VisitTaskInfo) v.getTag();
                        if(info.mCheckinTime != null && info.mCheckinTime.length() > 2){
                            gotoProductInfoActivity(info);
                        }else{
                            Actions.toastShort(this, this.getString(R.string.firstcheckin));
                        }*/
                        popCheckView((VisitTaskInfo) v.getTag(), v);
                    }
                    break;
                case R.id.checkpop_checkmap://地图
                    gotoMapActivity(mCheckingVisitTaskInfo);
                    break;
                case R.id.visittask_addstore: //新增门店列表
                	gotoStoreListActivity();
                    //gotoAddStoreActivity();
                    break;
                case R.id.visit_back:
                case R.id.visittask_back:
                    finish();
                    break;
                case R.id.checkpop_close:
                    if (mCheckView != null && mFrameLayout.indexOfChild(mCheckView) != -1) {
                        mFrameLayout.removeView(mCheckView);
                    }
                    break;
                case R.id.popcheck_blank:
                    break;
                case R.id.home_visitTast:
                	if(canVisit()){
                		popCheckView((VisitTaskInfo) v.getTag(), v);
                	}
                    break;
                case R.id.checkpop_editcrc:
                    if(mCheckView != null && mFrameLayout.indexOfChild(mCheckView) != -1){
                        mFrameLayout.removeView(mCheckView);
                    }
                    VisitTaskInfo info = (VisitTaskInfo) v.getTag();
                    gotoProductInfoActivity(info);
                    break;
                case R.id.checkpop_storepop:
                    gotoStoreInfoActivity((VisitTaskInfo) v.getTag());
                    break;
                case R.id.checkpop_put: //上传
                    if(mSyncCustomerData == null){
                        mSyncCustomerData = new PutCustomerData(this, this.getLayoutInflater(), mHandler, mFrameLayout);
                    }
                    VisitTaskInfo item = (VisitTaskInfo) v.getTag();
                    if(mCheckView != null && mFrameLayout.indexOfChild(mCheckView) != -1){
                        mFrameLayout.removeView(mCheckView);
                    }
                    mSyncCustomerData.statSync(item.id, item.mName);
                    break;
            }
        }
    }

    /**
     * 跳转门店CRC数据考核界面
     * @param info 门店信息
     */
    private void gotoProductInfoActivity(VisitTaskInfo info) {
        Intent intent = null;
        if (info.type == VisitTaskInfo.STORE_DEALER) {
            intent = new Intent(VisitTaskListActivity.this, DealerTaskListActivity.class);
        } else {
            intent = new Intent(VisitTaskListActivity.this, StoreEvaluationActivity.class);
        }
        Bundle bundle = new Bundle();
        bundle.putParcelable("info", info);
        intent.putExtras(bundle);
        startActivityForResult(intent, UPDATE_DB);
    }

    /**
     * 跳转门店数据调查界面
     * @param info 门店信息
     */
    private void gotoStoreInfoActivity(VisitTaskInfo info) {
        Intent intent = new Intent(VisitTaskListActivity.this, StoreInfoActivity.class);
        intent.putExtra(StoreInfoActivity.STR_TYPE, StoreInfoActivity.TYPE_FROMVISIT);
        intent.putExtra(StoreInfoActivity.STR_STOREID, info.id);
        startActivity(intent);
    }

    /**
     * 跳转门店地图界面
     * @param info 门店信息
     */
    private void gotoMapActivity(VisitTaskInfo info) {
        Intent intent = new Intent(VisitTaskListActivity.this, MyLocationActivity.class);
        intent.putExtra("lng", info.mLongitude/*121.5200*/);
        intent.putExtra("lat", info.mLatitude/*31.2996*/);
        intent.putExtra("name", info.mName);
        intent.putExtra("addr", info.mAddress/*"上海市杨浦区五角场店"*/);
        startActivity(intent);
    }

    /**
     * 跳转新增门店列表界面
     */
    private void gotoStoreListActivity(){
        Intent tent = new Intent(VisitTaskListActivity.this, AddedStoreListActivity.class);
        startActivity(tent);
    }

    private void gotoAddStoreActivity() {
        Intent intent = new Intent(VisitTaskListActivity.this, AddStoreActivity.class);
        startActivity(intent);
    }

    private void gotoNearStoreActivity() {
        Intent intent = new Intent(VisitTaskListActivity.this, NearStoreListActivity.class);
        startActivityForResult(intent, UPDATE_DB);
    }

    /**
     * 弹出门店拜访选择框
     * @param visitTaskInfo 门店信息
     * @param view 列表项View
     */
    private void popCheckView(VisitTaskInfo visitTaskInfo, View view) {
        if(mCheckView == null){
            mCheckView = getLayoutInflater().inflate(R.layout.layout_popcheck, null);
            mCheckView.setOnClickListener(this);
            ImageView close = (ImageView) mCheckView.findViewById(R.id.checkpop_close);
            close.setOnClickListener(this);
            Button map = (Button)mCheckView.findViewById(R.id.checkpop_checkmap);
            map.setOnClickListener(this);
        }
        TextView name = (TextView) mCheckView.findViewById(R.id.checkpop_title);
        name.setText(visitTaskInfo.mName);
        Button crc = (Button) mCheckView.findViewById(R.id.checkpop_editcrc);
        Button property = (Button) mCheckView.findViewById(R.id.checkpop_storepop);
        Button put = (Button) mCheckView.findViewById(R.id.checkpop_put);
        property.setTag(visitTaskInfo);
        crc.setTag(visitTaskInfo);
        put.setTag(visitTaskInfo);
        if(Actions.DEBUG){
            Log.e("zhu","time="+visitTaskInfo.mCheckinTime);
        }
        setButtonEnable(crc, true, R.drawable.crc);

        if (visitTaskInfo.iProperty == 0) {
            setButtonEnable(property, false, R.drawable.property);
        } else {
            setButtonEnable(property, true, R.drawable.property_blue);
        }

        if(visitTaskInfo.canPut){
            setButtonEnable(put, true, R.drawable.icon_shangchuan);
        }else{
            setButtonEnable(put, false, R.drawable.icon_shangchuan_normal);
        }
        mCheckingButtom = (ImageView) view.findViewById(R.id.home_visitTast);
        mCheckingVisitTaskInfo = visitTaskInfo;
        mFrameLayout.addView(mCheckView);
    }

    /**
     * 设置按钮状态
     * @param button 按钮
     * @param isEnabled 开启
     * @param resId 图片资源ID
     */
    private void setButtonEnable(Button button, boolean isEnabled, int resId){
        if(isEnabled){
            button.setEnabled(true);
            button.setCompoundDrawablesWithIntrinsicBounds(null, this.getResources().getDrawable(resId), null, null);
            button.setTextColor(getResources().getColor(R.color.visit_blue));
            button.setOnClickListener(this);
        }else{
            button.setEnabled(false);
            button.setCompoundDrawablesWithIntrinsicBounds(null, this.getResources().getDrawable(resId), null, null);
            button.setTextColor(getResources().getColor(R.color.visit_gray));
            button.setOnClickListener(null);
        }
    }

    public void onDestroy() {
        super.onDestroy();
    }

    /**
     * 按键事件处理
     */
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            if(!doBack()){
                finish();
            }
            return true;
        }
        return false;
    }

    public boolean dispatchKeyEvent(KeyEvent event){
		if(isChecking){
			return true;
		}
		return super.dispatchKeyEvent(event);
	}

	public boolean dispatchTouchEvent(MotionEvent ev){
		if(isChecking){
			return true;
		}
		return super.dispatchTouchEvent(ev);
	}

	/**
     * 返回事件处理
     */
    private boolean doBack(){
        if(mFrameLayout.indexOfChild(mCheckView) != -1){
            mFrameLayout.removeView(mCheckView);
            return true;
        }
        if(mSyncCustomerData != null && mSyncCustomerData.isSync()){
            return true;
        }
        return false;
    }

    /**
     * 签入签出
     * @param type 类型 签入OR签出
     */
    private void startCheck(int type){
    	mCurLocation = null;
    	isChecking = true;
    	mCurCheckType = type;
    	mCheckView.findViewById(R.id.checkpop_botton).setVisibility(View.INVISIBLE);
    	mCheckView.findViewById(R.id.checkpop_close).setVisibility(View.INVISIBLE);
    	mCheckView.findViewById(R.id.checkpop_animation).setVisibility(View.VISIBLE);
    	TextView text = (TextView)mCheckView.findViewById(R.id.checkpop_animationText);
    	if(mCurCheckType == CHECK_IN){
    		text.setText(R.string.checkining);
    	}else{
    		text.setText(R.string.checkouting);
    	}
    	ImageView view = (ImageView)mCheckView.findViewById(R.id.checkpop_animationImage);
    	mAnimation = (AnimationDrawable) view.getBackground();
    	mAnimation.setLevel(0);
    	mAnimation.start();
    	if(mMyLocation == null){
    		mMyLocation = new MyLocation(this, false, false);
    	}
    	mMyLocation.getLocation(locationResult, true);
    }

    /**
     * 签出OR签入结束
     */
    private void stopCheck(){
        boolean success = saveData();
        if(mCurCheckType == CHECK_IN){
            mCheckingButtom.setImageResource(R.drawable.icon_checkout);
        }else{
            //mCheckingButtom.setImageResource(R.drawable.pop_check_disable);
            mCheckingButtom.setEnabled(false);
        }
        isChecking = false;
        mAnimation.stop();
        mFrameLayout.removeView(mCheckView);
        if(mCheckingVisitTaskInfo.isVisited){
            mVisitedCount++;
            updateInfoTextview(mVisitTaskList.size(), mVisitedCount);
            updateCheckView(mCheckingVisitTaskInfo);
        }
        mCheckingVisitTaskInfo = null;
        mCheckingButtom = null;
        mCheckView.findViewById(R.id.checkpop_botton).setVisibility(View.VISIBLE);
        mCheckView.findViewById(R.id.checkpop_close).setVisibility(View.VISIBLE);
        mCheckView.findViewById(R.id.checkpop_animation).setVisibility(View.INVISIBLE);
    }

    /**
     * 定位结果
     */
    public LocationResult locationResult = new LocationResult() {

        public void gotLocation(final Location location) {
            // Got the location!
            if (location != null) {
                mCurLocation = location;
            }
            stopCheck();
        }
    };

    /**
     * 保存签入OR签出数据
     */
    private boolean saveData(){
        double lat = 0;
        double lng = 0;
        if(mCurLocation != null){
            lat = mCurLocation.getLatitude();
            lng = mCurLocation.getLongitude();
        }
        if(lat == 0 && lng == 0){
            Location location = Util.mGetGpsLocation.getLastLocation();
            if(location != null){
                lat = location.getLatitude();
                lng = location.getLongitude();
            }
        }
        if(mCurCheckType == CHECK_IN){
            mCheckingVisitTaskInfo.mCheckinTime = String.valueOf(mMyLocation.getCurrentTime()/*System.currentTimeMillis()*/);
            boolean success = Util.saveStoresCheckinInfo(this, mCheckingVisitTaskInfo, lat, lng, false);
            if(success){
                if(lat == 0 && lng == 0){
                    Actions.toastShort(this, getString(R.string.checkinsuccess_fail));
                }else{
                    Actions.toastShort(this, getString(R.string.checkin_success));
                }
                return true;
            }else{
                mCheckingVisitTaskInfo.mCheckinTime = "";
                return false;
            }
        }else{
            mCheckingVisitTaskInfo.mCheckoutTime = String.valueOf(mMyLocation.getCurrentTime()/*System.currentTimeMillis()*/);
            boolean success = Util.saveStoresCheckoutInfo(this, mCheckingVisitTaskInfo, lat, lng);
            if(success){
                if(lat == 0 && lng == 0){
                    Actions.toastShort(this, getString(R.string.checkoutsuccess_fail));
                }else{
                    Actions.toastShort(this, getString(R.string.checkout_success));
                }
                mCheckingVisitTaskInfo.isVisited = true;
                return true;
            }else{
                mCheckingVisitTaskInfo.mCheckoutTime = "";
                return false;
            }
        }
    }

    /**
     * 更新列表项数据
     * @param updateInfo 门店信息
     */
    private void updateCheckView(VisitTaskInfo updateInfo){
        int index = getViewIndex(updateInfo);
        if(index != -1){
            mBodyLinearLayout.removeViewAt(index);
        }
        VisitTaskInfo info = mVisitTaskList.get(index);
        View view = null;
        if(info.type == VisitTaskInfo.STORE_DEALER){
            view = getDealerVisitedTaskItem(info);
        }else{
            view = getVisitedTaskItem(info);
        }
        mBodyLinearLayout.addView(view, index);
    }

    /**
     * 获取拜访门店界面在列表中的索引
     * @param updateInfo 门店信息
     */
    private int getViewIndex(VisitTaskInfo updateInfo){
        VisitTaskInfo info = null;
        for(int i = 0; i < mVisitTaskList.size(); i++){
            info = mVisitTaskList.get(i);
            if(info.id == updateInfo.id){
                return i;
            }
        }
        return -1;
    }

    private ObservableScrollView.ScrollViewListener mScrollViewListener = new ObservableScrollView.ScrollViewListener(){

        @Override
        public void onScrollChanged(ObservableScrollView scrollView, int x, int y, int oldx,
                int oldy) {
            // TODO Auto-generated method stub
            if(Actions.DEBUG){
                Log.e("zhu","onScrollChanged="+ Math.abs(y - oldy));
            }
            if(Math.abs(y - oldy) > 1){
                mScollClew.setVisibility(View.GONE);
            }
        }

    };

    private final class DataQueryHandler extends AsyncQueryHandler {
        public DataQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
                case TASK_LIST_QUERY_TOKEN:
                    updateList(cursor);
                    break;
                case CNAME_LIST_QUERY_TOKEN:
                	updateStoreInfoList(cursor);
                    break;
                case CREMIND_LIST_QUERY_TOKEN:
                    updateStoreRemindInfoList(cursor);
                    break;
                default:
                    Log.e(TAG, "onQueryComplete called with unknown token " + token);
            }
        }

        @Override
        protected void onDeleteComplete(int token, Object cookie, int result) {
            switch (token) {
                case TASK_LIST_DELETE_TOKEN:
                    break;
                default:
                    Log.e(TAG, "onDeleteComplete called with unknown token " + token);
            }
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case UPDATE_DB:
                startTaskListAsyncQuery();
                break;
        }
    }

    private boolean canVisit(){
        return true;
    }

    /**
     * 上传结果返回
     */
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case PutCustomerData.SYNC_SUCCESSEND:
                    startTaskListAsyncQuery();
                    mSyncCustomerData.remoView();
                    Actions.toastShort(VisitTaskListActivity.this, VisitTaskListActivity.this.getString(R.string.putdatasuccess));
                    break;
                case PutCustomerData.SYNC_FAILEDEND:
                    mSyncCustomerData.remoView();
                    Actions.toastShort(VisitTaskListActivity.this, VisitTaskListActivity.this.getString(R.string.putdatafail));
                    break;
            }
        }
    };
}
